<?php

require_once 'SmartL/Zend/Controller/Action.php';
require_once 'Db/Shop/Record/Order.php';
require_once 'Db/Shop/Record/OrderItem.php';
require_once 'Db/Shop/Record/BasketItem.php';
require_once 'Db/Shop/Record/Product.php';

class OrdersController extends SmartL_Zend_Controller_Action  
{
    /**
     * List of user's orders.
     * Parameters: *user
     */
    public function userOrdersAction()
    {
        $user = Zend_Auth::getInstance()->getIdentity();
        if (empty($user)) {
            $this->_helper->redirector->goto("index","index");
        }
        
        $query = new Doctrine_Query();
        $orders = $query->select("o.*, i.price, i.amount")
                        ->from("Db_Shop_Record_Order o")
                        ->leftJoin("o.Items i")     
                        ->orderBy("o.timecreated DESC")
												->where('o.userId = ?', $user->id)
                        ->execute(array(),Doctrine::HYDRATE_ARRAY);
  
        foreach ($orders as &$order) {
            $orderPrice = 0;
            foreach ($order['Items'] as $item) {
                $orderPrice += $item['price'] * $item['amount']; 
            }
            unset($item['Items']);
            $order['price'] = $orderPrice;
        }
        
        $this->view->orders = $orders;  
    }
    
    /**
     * Order detail.
     * Parameters: order id, *user   
     */
    public function orderDetailAction()
    {
        $user = Zend_Auth::getInstance()->getIdentity();
        if (empty($user)) {
            $this->_helper->redirector->goto("index","index");
        }
        
        if ($this->_hasParam('id')) {
            $query = new Doctrine_Query();
            $order = 
                  $query->select("*")
                  ->from("Db_Shop_Record_Order o")   
                  ->leftJoin('Db_Shop_Record_OrderItem i')       
                  ->where("o.userId = ?", array($user->id))
                  ->addWhere("o.id = ?", (integer)$this->_getParam('id'))
                  ->execute()->getFirst();     
            $totalPrice = 0;
            if (!empty($order)) {
                foreach ($order->Items as $item) {
                    $itemTotalPrice = $item->price * $item->amount;
                    $item->mapValue('totalPrice', $itemTotalPrice);  
                    $totalPrice += $itemTotalPrice;                     
                }
            }
            $this->view->orderId = $this->_getParam('id');
            $this->view->order = $order;
            $this->view->orderItems = $order->Items;
            $this->view->order->mapValue('totalPrice', $totalPrice);
        }
    }
    
    /**
     * Order overview before submitting (sending).
     * Parameters: *user
     */
    public function orderOverviewAction()
    {
        $user = Zend_Auth::getInstance()->getIdentity();
        if (empty($user)) {
            $this->_helper->redirector->goto("index","index");
        }
        
        $query = new Doctrine_Query();
        $orderItems = 
              $query->select("b.productId, b.userId, p.price, t.name")
              ->from("Db_Shop_Record_BasketItem b")
              ->leftJoin("b.Product p")  
              ->leftJoin("p.Translation t")              
              ->where("b.userId = ?", array($user->id))
              ->orderBy("t.name ASC")
              ->execute();     
        
        if (count($orderItems) == 0) {
            $this->_helper->redirector->goto("items-list","user-basket");
        }        
        $this->view->orderItems = $orderItems;
        $this->view->totalPrice = 0;
        foreach ($this->view->orderItems as $item) {
            $itemTotalPrice = $item->Product->price*$item->amount;
            $item->mapValue('price',$itemTotalPrice);
            $this->view->totalPrice += $itemTotalPrice;
        }
    }
    
    /**
     * Create new order.
     * Parameters: *user
     */
    public function createOrderAction()
    {
        $user = Zend_Auth::getInstance()->getIdentity();
        if (empty($user)) {
            $this->_helper->redirector->goto("index","index");
        }
        
    	$order = new Db_Shop_Record_Order();
    	$order->userId = $user->id;
    	$order->status = $order->getTable()->enumIndex('status','Waiting');
    	$order->timecreated = new Doctrine_Expression('NOW()');	// Just to make sure this value won't stay NULL
    	
    	$query = new Doctrine_Query();
        $basketItems = 
              $query->select("i.amount, p.price, t.name")
              ->from("Db_Shop_Record_BasketItem i")
              ->leftJoin("i.Product p")  
              ->leftJoin("p.Translation t")              
              ->where("i.userId = ?", array($user->id))
              ->execute();
    	if (count($basketItems)>0) {
        	foreach ($basketItems as $item) {
        		$orderItem = new Db_Shop_Record_OrderItem();
        		$orderItem->amount = $item->amount;
        		$orderItem->price = $item->Product->price;
        		foreach ($this->application->getSupportedLanguages() as $language) {
        			if ( isset($item->Product->Translation[$language->getId()]) ) {
        				$orderItem->Translation[$language->getId()]->description = 
        					$item->Product->Translation[$language->getId()]->name; 
        			}
        		}
        		$order->Items[] = $orderItem;        		
        	}        	
        	$query = new Doctrine_Query();
        	$conn = $query->getConnection();
        	        	
        	$conn->beginTransaction(); // Create transaction
        	try {
        	    $order->save();
        	    //delete basket
        		
            	$query->delete()
            		->from('Db_Shop_Record_BasketItem i')
            		->where('i.userId = ?', array($user->id))
            		->execute();
            		
                $conn->commit();
        	} catch(Doctrine_Exception $e) {
                $conn->rollback();
                        		var_dump($e->getMessage());
        		die("jsem tu-exception");
            }
    	}
    	else { // No products in basket
            $this->_helper->redirector->goto("items-list","user-basket");
        }  
    	$this->_helper->redirector->goto("user-orders","orders");
    }
}

